import React, {Component} from 'react'
import {View, Text, ScrollView, TouchableOpacity, Alert, Platform} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import Spinner from 'react-native-spinkit'
import styles, {BLUE} from '../../config/styles'
import {AudioRecorder, AudioUtils} from 'react-native-audio'
import {Aws3UploadApi, PostTaskAudioApi} from '../../config/api'
var Sound = require('react-native-sound');

class StudentDoHomework extends Component {
    static navigationOptions = ({navigation}) => {
        return {
            title: navigation.state.params.title
        }
    }


    constructor (props) {
        super(props)
        const {params} = props.navigation.state
        if (params.current_audio_path) {
            this.voice = new Sound(params.current_audio_path, '', (error) => {});
        }

        this.state = {
            task_id: params.task_id,
            content: params.content,
            rerecordAllow: params.rerecordAllow, //是否允许重新录制
            contentDisplay: params.contentDisplay, //是否显示课文
            status: params.current_audio_path ? 'recorded' : null, // null | recorded | recording | playing
            audioPathLocal: null,
            audioPathAws: params.current_audio_path || null,
            submitting: false,
            afterRecord: params.afterRecord
        }
    }

    componentWillUnmount () {
        if (this.voice != undefined) this.voice.release()
    }

    submit = () => {
        const {audioPathLocal, task_id, submitting, afterRecord, audioPathAws} = this.state
        if (submitting) return
        let name = this._get_name()
        this.setState({submitting: true})
        if (audioPathAws != null && audioPathLocal == null) {
            //说明没录
            this.props.navigation.goBack()
        } else {
            Aws3UploadApi(`${name}.aac`, audioPathLocal, 'audio/aac').then((result) => {
                let attachment = {url: result.awsPath, type: 'audio', name: name, sub_type: 1}
                this.setState({submitting: false})
                afterRecord(attachment)
                this.props.navigation.goBack()
                // PostTaskAudioApi(task_id, {
                //     attachments: [attachment]
                // }).then((data) => {
                //     this.setState({submitting: false})
                //     afterRecord(attachment)
                //     this.props.navigation.goBack()
                // })
            })
        }
       
    }

    _get_name = () => {
        let date = new Date()
        let name = date.getTime().toString()
        name = name.substr(name.length - 6, 6)
        return name
    }

    //开始录音
    startRecord = () => {
        this.setState({status: 'recording'}, () => {
            //初始化音频路径
            let date = new Date()
            const audioPath = AudioUtils.DocumentDirectoryPath + `/${date.getTime()}.aac`
            AudioRecorder.prepareRecordingAtPath(audioPath, {
                SampleRate: 22050,
                Channels: 1,
                AudioQuality: "Low",
                AudioEncoding: "aac",
                AudioEncodingBitRate: 32000
            });

            //ios和安卓不同，需要额外起一个监听来获取结束后的filePath
            AudioRecorder.onFinished = (data) => {
                // Android callback comes in the form of a promise instead.
                if (Platform.OS === 'ios') {
                    this._finishRecording(data.audioFileURL.replace(/file:\/\//, ''));
                }
            };

            AudioRecorder.startRecording()
        })
    }

    //结束录音
    stopRecord = () => {
        this.setState({status: 'recorded'}, async () => {
            let filePath = await AudioRecorder.stopRecording();
            if (Platform.OS === 'android') {
                filePath = 'file://' + filePath
                this._finishRecording(filePath)
            }
        })
    }

    _finishRecording = (filePath) => {
        let _filePath = filePath.replace(/file:\/\//, '')
        this.voice = new Sound(_filePath, '', (error) => {
            if (error) {
                console.log(error, 'error')
                alert(error)
                return;
            }
        });
        this.state.audioPathLocal = filePath
    }

    //播放录音
    playVoice = () => {
        this.setState({status: 'playing'}, () => {
            this.voice.play((success) => {
                if (success) {
                    this.setState({
                        status: 'recorded'
                    })
                } else {
                  alert('出错')
                }
            });
        })
    }

    //暂停播放
    stopVoice = () => {
        this.voice.stop()
        this.setState({status: 'recorded'})      
    }

    resetRecord = () => {
        const {rerecordAllow} = this.state
        if (rerecordAllow == true) 
            this.setState({status: null}, () => {
                if (this.voice != undefined) this.voice.release()
            })
        else 
            Toast.show('当前作业状态无法重新录制')
            return    
    }

    //第三个按钮的模板
    submitButtonTemplate = () => {
        const {status} = this.state
        if (status == 'recorded' || status == 'playing') {
            return (
                <TouchableOpacity 
                    style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
                    onPress={this.submit}
                >
                    <Icon name={'md-checkmark'} size={32} color={'#00FF00'} />
                </TouchableOpacity>
            )
        } else {
            return (
                <TouchableOpacity
                    onPress={() => {this.props.navigation.goBack()}}
                    style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
                >
                    <Icon name={'md-close'} size={32} />
                </TouchableOpacity>
            )
        }
    }

    //中间按钮的模板
    middleButtonTemplate = () => {
        switch(this.state.status) {
            case null:
                return(
                    <TouchableOpacity 
                        style={[styles.icon_container, styles.large_icon, {backgroundColor: BLUE}]}
                        onPress={this.startRecord}
                    >
                        <View style={{justifyContent: 'center', alignItems: 'center', padding: 20, flex: 1}}>
                            <Icon name={'ios-mic-outline'} size={40} color={'white'} />
                        </View>
                    </TouchableOpacity>   
                )
            case 'recorded':
                return(
                    <TouchableOpacity 
                        style={[styles.icon_container, styles.large_icon, {backgroundColor: BLUE}]}
                        onPress={this.playVoice}
                    >
                        <View style={{justifyContent: 'center', alignItems: 'center', flex: 1, paddingLeft: 5, paddingTop: 5}}>
                            <Icon name={'md-play'} size={40} color={'white'}  />
                        </View>
                    </TouchableOpacity>   
                )    
            case 'recording':
                return(
                    <TouchableOpacity
                        style={[styles.icon_container, styles.large_icon, {backgroundColor: '#00FF00'}]}
                        onPress={this.stopRecord}
                    >
                        <View style={{justifyContent: 'center', alignItems: 'center', flex: 1}}>
                            <Spinner type={'Wave'} color={'white'} />
                        </View>
                    </TouchableOpacity>   
                )
            case 'playing':
                return(
                    <TouchableOpacity 
                        style={[styles.icon_container,styles.large_icon, {backgroundColor: '#00FF00'}]}
                        onPress={this.stopVoice}
                    >
                        <View style={{justifyContent: 'center', alignItems: 'center', padding: 12}}>
                            <Spinner type={'Bounce'} color={'white'} />
                        </View>
                    </TouchableOpacity>
                )
            default:
                return null        
        }
    }

    render () {
        const {content, contentDisplay} = this.state
        return (
            <View style={{flex: 1}}>
                <ScrollView contentContainerStyle={{alignItems: 'center', padding: 20}} style={{backgroundColor: 'white'}}>
                    {
                       contentDisplay ? (<Text style={{fontSize: 24}}>{this.state.content}</Text>) : null
                    }
                </ScrollView>

                <View style={{position: 'absolute', bottom: 0, padding: 20, flex: 1, backgroundColor: 'white', flexDirection: 'row'}}>
                    <TouchableOpacity 
                        style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
                        onPress={() => {
                            Alert.alert('确认', '确定重新录制吗？',[
                                {text: '取消', onPress: () => {}},
                                {text: '确定', onPress: () => {this.resetRecord()}}
                            ])
                        }}
                    >
                        <Icon name={'md-sync'} size={32} />
                    </TouchableOpacity>

                   {this.middleButtonTemplate()}

                   {this.submitButtonTemplate()}
                </View>
            </View>
          
        )
    }
}

export default StudentDoHomework